import { createRouter, createWebHistory } from "vue-router"
// 只导入必要的组件，避免图标导入错误
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/LoginView.vue"),
    meta: {
      title: "登录",
      requiresAuth: false
    }
  },
  {
    path: "/debug-login",
    name: "debugLogin",
    component: () => import("../views/DebugLoginStatus.vue"),
    meta: {
      title: "登录状态调试",
      requiresAuth: false
    }
  },
  {
    path: "/",
    name: "dashboard",
    component: () => import("../views/Dashboard.vue"),
    meta: {
      title: "仪表盘",
      icon: "el-icon-data-line",
      requiresAuth: true
    }
  },
  // 安全管理模块路由组
  {
    path: "/security",
    name: "security",
    meta: {
      title: "安全管理",
      icon: "el-icon-shield"
    },
    children: [
      {
          path: "user-management",
          name: "userManagement",
          component: () => import("../views/user/UserManagementView.vue"),
          meta: {
            title: "用户管理",
            requiresAuth: true
          }
        },
      {
        path: "dashboard",
        name: "security-dashboard",
        component: () => import("../views/SecurityDashboard.vue"),
        meta: {
          title: "安全概览",
          icon: "el-icon-data-line"
        }
      },
      {
        path: "compliance",
        name: "security-compliance",
        component: () => import("../views/SecurityCompliance.vue"),
        meta: {
          title: "合规管理",
          icon: "el-icon-document-checked"
        }
      },
      {
        path: "knowledge-base",
        name: "security-knowledge-base",
        component: () => import("../views/SecurityKnowledgeBase.vue"),
        meta: {
          title: "知识库",
          icon: "el-icon-document"
        }
      },
      {
        path: "incident-response",
        name: "security-incident-response",
        component: () => import("../views/SecurityIncidentResponse.vue"),
        meta: {
          title: "事件响应",
          icon: "el-icon-warning"
        }
      },
      {
        path: "report",
        name: "security-report",
        component: () => import("../views/SecurityReportNew.vue"),
        meta: {
          title: "报告生成",
          icon: "el-icon-printer"
        }
      },
      {
        path: "baseline",
        name: "security-baseline",
        component: () => import("../views/SecurityBaseline.vue"),
        meta: {
          title: "基线配置",
          icon: "el-icon-aim"
        }
      },
      {
        path: "vulnerability",
        name: "security-vulnerability",
        component: () => import("../views/SecurityVulnerability.vue"),
        meta: {
          title: "漏洞管理",
          icon: "el-icon-search"
        }
      },
      {
        path: "script-management",
        name: "script-management",
        component: () => import("../views/ScriptManagement.vue"),
        meta: {
          title: "脚本管理",
          icon: "el-icon-edit-outline",
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: "/scan",
    name: "scan",
    component: () => import("../views/ScanView.vue"),
    meta: {
      title: "新建扫描",
      icon: "el-icon-search",
      requiresAuth: true
    }
  },
  {
    path: "/scan/list",
    name: "scan-list",
    component: () => import("../views/ScanListView.vue"),
    meta: {
      title: "扫描列表",
      icon: "el-icon-document",
      requiresAuth: true
    }
  },
  {
    path: "/scan/history",
    name: "scan-history",
    component: () => import("../views/ScanHistoryView.vue"),
    meta: {
      title: "扫描历史",
      icon: "el-icon-time",
      requiresAuth: true
    }
  },
  {
    path: "/results",
    name: "results",
    component: () => import("../views/ResultsView.vue"),
    meta: {
      title: "扫描结果",
      icon: "el-icon-document-checked",
      requiresAuth: true
    }
  },
  {
    path: "/attack-path",
    name: "attack-path",
    component: () => import("../views/AttackPathView.vue"),
    meta: {
      title: "攻击路径",
      icon: "el-icon-link",
      requiresAuth: true
    }
  },
  {
    path: "/suggestions",
    name: "suggestions",
    component: () => import("../views/SuggestionsView.vue"),
    meta: {
      title: "修复建议",
      icon: "el-icon-s-tools",
      requiresAuth: true
    }
  },
  {
    path: "/target-range",
    name: "target-range",
    component: () => import("../views/TargetRangeView.vue"),
    meta: {
      title: "靶场系统",
      icon: "el-icon-aim",
      requiresAuth: true
    }
  },
  {
    path: "/statistics",
    name: "statistics",
    component: () => import("../views/StatisticsView.vue"),
    meta: {
      title: "统计分析",
      icon: "el-icon-data-analysis",
      requiresAuth: true
    }
  },
  {
    path: "/settings",
    name: "settings",
    component: () => import("../views/SettingsView.vue"),
    meta: {
      title: "系统设置",
      icon: "el-icon-setting",
      requiresAuth: true
    }
  },
  // 个人中心路由
  {
    path: "/profile",
    name: "profile",
    component: () => import("../views/ProfileView.vue"),
    meta: {
      title: "个人中心",
      icon: "el-icon-user",
      requiresAuth: true
    }
  },
  // 捕获所有未匹配的路由，重定向到登录页
  {
    path: "/:pathMatch(.*)*",
    redirect: "/login"
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  // 添加滚动行为
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 漏洞扫描系统`
  } else {
    document.title = '漏洞扫描系统'
  }
  
  // 安全重置路由错误状态
  if (router.app) {
    router.app._routeError = false
  }
  
  // 检查是否需要认证
  const requiresAuth = to.meta.requiresAuth !== false // 默认需要认证
  const isLoggedIn = !!localStorage.getItem('token')
  
  if (requiresAuth && !isLoggedIn) {
    // 需要认证但未登录，重定向到登录页
    next({ path: '/login', query: { redirect: to.fullPath } })
  } else if (to.path === '/login' && isLoggedIn) {
    // 已登录且访问登录页，重定向到首页
    next({ path: '/' })
  } else {
    // 正常路由
    next()
  }
})

// 全局解析守卫 - 确保路由组件加载完成
router.beforeResolve((to, from, next) => {
  next()
})

// 全局后置守卫
router.afterEach((to, from, failure) => {
  if (failure) {
    console.error('路由导航失败:', failure)
    ElMessage.error('页面加载失败，请重试')
  }
})

// 错误处理
router.onError((error) => {
  console.error('路由错误:', error)
  ElMessage.error('页面加载失败，请重试')
  // 标记路由错误状态
  try {
    if (router && router.app) {
      router.app._routeError = true
    }
  } catch (err) {
    console.warn('无法设置路由错误状态:', err)
  }
})

export default router
